package com.hikeen.launcherx;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dou361.dialogui.DialogUIUtils;
import com.google.gson.Gson;
import com.hikeen.launcherx.adapter.AppSelectAdapter;
import com.hikeen.launcherx.adapter.UtilsAppAdapter;
import com.hikeen.launcherx.bean.AppInfo;
import com.hikeen.launcherx.bean.AppInfoss;
import com.hikeen.launcherx.floatwindow.EventMessage;
import com.hikeen.launcherx.ui.MainActivity3;
import com.hikeen.launcherx.utils.AppUtils;
import com.hikeen.launcherx.utils.DragImageView;
import com.hikeen.launcherx.utils.FileImageUtils;
import com.hikeen.launcherx.utils.GsonUtils;
import com.hikeen.launcherx.utils.SPUtils;
import com.hikeen.launcherx.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


public class TwoFramgent extends Fragment implements View.OnClickListener {
    private String TAG = "T";

    private TextView text;
    private TextView tv_date;
    private TextView tv_week;

    private int weekday;
    private TextView tv_shifen;
    private TextView tv_miao;
    private TextView tv_pm;


    private int TIME = 1000;  //每隔1s执行一次.

    Handler handler = new Handler();
    private Runnable runnable;
    private LinearLayout ll_tab1;
    private LinearLayout ll_tab2;
    private LinearLayout ll_tab3;
    private Intent intent;
    private ArrayList<AppInfo> allApp;
    private ArrayList<AppInfo> newallApp;
    private UtilsAppAdapter allMyAdapater;
    private RecyclerView app_recycle;
    private LinearLayoutManager linearLayoutManager;
    private DragImageView xuanfu_pic;
    private ImageView image_shang;
    private ImageView image_xia;
    private ImageView image_zuo;
    private ImageView image_you;
    private Context mcontext;
    private Dialog dialogs;
    private List<AppInfo> testlist;
    private int pos;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_two_layout, container, false);
        mcontext = container.getContext();
        initView(view);
        return view;
    }


    private void initView(View view) {


        app_recycle = view.findViewById(R.id.app_recycle);
        text = (TextView) view.findViewById(R.id.text);
        tv_date = (TextView) view.findViewById(R.id.tv_date);
        tv_week = (TextView) view.findViewById(R.id.tv_week);

        tv_shifen = (TextView) view.findViewById(R.id.tv_shifen);
        tv_miao = (TextView) view.findViewById(R.id.tv_miao);
        tv_pm = (TextView) view.findViewById(R.id.tv_pm);

        //白板
        ll_tab1 = (LinearLayout) view.findViewById(R.id.ll_tab1);
        //文件
        ll_tab2 = (LinearLayout) view.findViewById(R.id.ll_tab2);
        //分享
        ll_tab3 = (LinearLayout) view.findViewById(R.id.ll_tab3);
        ll_tab1.setOnClickListener(this);
        ll_tab2.setOnClickListener(this);
        ll_tab3.setOnClickListener(this);


        //获取当前时间


        long time = System.currentTimeMillis();
        final Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(time);
        int nian = mCalendar.get(Calendar.YEAR);
        int yue = mCalendar.get(Calendar.MONTH) + 1;
        int ri = mCalendar.get(Calendar.DAY_OF_MONTH);


//        Log.e("initView", "initView: " + nian + "---" + yue + "---" + ri);
        //获取今天周几
        getWeek();


        mCalendar.setTimeInMillis(time);
        int miao = mCalendar.get(Calendar.SECOND);
        int shi = mCalendar.get(Calendar.HOUR);
        int fen = mCalendar.get(Calendar.MINUTE);
        tv_shifen.setText((shi < 10 ? "0" + shi : shi) + ":" + (fen < 10 ? "0" + fen : fen));
        tv_miao.setText(":" + (miao < 10 ? "0" + miao : miao));


        //动态设置秒
        runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    //获取今天周几
                    getWeek();
                    //获取当前时间
                    long time = System.currentTimeMillis();
                    final Calendar mCalendar = Calendar.getInstance();
                    mCalendar.setTimeInMillis(time);
                    int nian = mCalendar.get(Calendar.YEAR);
                    int yue = mCalendar.get(Calendar.MONTH) + 1;
                    int ri = mCalendar.get(Calendar.DAY_OF_MONTH);

                    int shi = mCalendar.get(Calendar.HOUR);
                    int fen = mCalendar.get(Calendar.MINUTE);
                    int miao = mCalendar.get(Calendar.SECOND);


                    int apm = mCalendar.get(Calendar.AM_PM);
//        apm=0 表示上午，apm=1表示下午。
                    if (apm == 0) {
                        tv_pm.setText(getResources().getString(R.string.day_am));
                    } else {
                        tv_pm.setText(getResources().getString(R.string.day_pm));
                        if (DateFormat.is24HourFormat(getContext())) {
                            shi = shi + 12;
                        }
                    }

                    tv_shifen.setText((shi < 10 ? "0" + shi : shi) + ":" + (fen < 10 ? "0" + fen : fen));
                    tv_miao.setText(":" + (miao < 10 ? "0" + miao : miao));

//                    Log.e("initView--- ", "initView:--- " + nian + "---" + yue + "---" + ri);
                    setTime(tv_date, nian + "", yue + "", ri + "");

                    if (weekday == 2) {
                        tv_week.setText(getResources().getString(R.string.day_1));
                    } else if (weekday == 3) {
                        tv_week.setText(getResources().getString(R.string.day_2));

                    } else if (weekday == 4) {
                        tv_week.setText(getResources().getString(R.string.day_3));

                    } else if (weekday == 5) {
                        tv_week.setText(getResources().getString(R.string.day_4));

                    } else if (weekday == 6) {
                        tv_week.setText(getResources().getString(R.string.day_5));

                    } else if (weekday == 7) {
                        tv_week.setText(getResources().getString(R.string.day_6));

                    } else if (weekday == 1) {
                        tv_week.setText(getResources().getString(R.string.day_7));
                    }
                    handler.postDelayed(this, TIME);
//                    Log.e("initView", "initView: "+"执行了"+miao+"----------"+mCalendar.get(Calendar.SECOND));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        handler.postDelayed(runnable, TIME);

        chushihua();

    }

    public void setTime(TextView textView, String year, String month, String day) {
        textView.setText(year + " / " + month + " / " + day);
    }

    public void chushihua() {


        //获取过滤过的应用
        allApp = new ArrayList<AppInfo>();
        allApp = AppUtils.getAppInfo1(getContext());
        String s = "";
        try {
            s = SPUtils.getString("applist", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("接收appinfo", "onMessageEvent: " + s);

        List<AppInfoss> appInfosses = GsonUtils.getPersons(s, AppInfoss.class);
        newallApp = new ArrayList<>();
        if (appInfosses != null && appInfosses.size() > 0) {
//            for (int i = 0; i < allApp.size(); i++) {
//                for (int j = 0; j < appInfosses.size(); j++) {
//                    if (allApp.get(i).getAppName().equals(appInfosses.get(j).getAppName()) &&
//                            allApp.get(i).getPackageName().equals(appInfosses.get(j).getPackageName())) {
//                        newallApp.add(allApp.get(i));
//                        ToastUtils.show("chishihua-------for");
//                    }
//                }
//            }


            for (int i = 0; i < appInfosses.size(); i++) {
                for (int j = 0; j < allApp.size(); j++) {
                    if (allApp.get(j).getPackageName().equals("com.hikeen.sidebar")) {
                        continue;
                    }

                    if (allApp.get(j).getAppName().equals(appInfosses.get(i).getAppName()) ||
                            allApp.get(j).getPackageName().equals(appInfosses.get(i).getPackageName())) {
                        newallApp.add(allApp.get(j));

                    }
                }
            }
        }

        initQuickApp();

        if (newallApp.size() < 10) {
            AppInfo appInfos = new AppInfo();
            appInfos.setAppIcon(getResources().getDrawable(R.drawable.ic_add));
            newallApp.add(appInfos);
        }


        allMyAdapater = new UtilsAppAdapter(getContext(), newallApp);

        linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        app_recycle.setLayoutManager(linearLayoutManager);


        app_recycle.setAdapter(allMyAdapater);

        //点击跳转apk
        allMyAdapater.setOnItemClickListener(new UtilsAppAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                Log.e("dsadsadsa", "dsadsadsa: " + position + "-------------------" + (allApp.size() - 1));
                // ToastUtils.show("dsadsadsa: "+position+"-------------------"+(newallApp.size()-1));
                if (position == newallApp.size() - 1 && position < 10) {
                    //最后一跳点击添加
                    // ToastUtils.show("最后一条 添加");
                    //自定义弹框
                    View rootView = View.inflate(getContext(), R.layout.layout_app_sel, null);
                    RecyclerView recycle = rootView.findViewById(R.id.recycle);
                    linearLayoutManager = new LinearLayoutManager(getContext());
                    linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
                    recycle.setLayoutManager(linearLayoutManager);
                    //需要过滤掉想要加入的APP列表  到这里
                    testlist = AppUtils.getAppInfo1(getContext());

                    AppSelectAdapter appSelectAdapter = new AppSelectAdapter(mcontext, testlist);
                    recycle.setAdapter(appSelectAdapter);
                    dialogs = DialogUIUtils.showCustomAlert(getContext(), rootView).show();

                    appSelectAdapter.setOnItemClickListener(new AppSelectAdapter.OnItemClickListener() {
                        @Override
                        public void onClick(int position) {
                            Log.d(TAG, "onClick: testlist.get(position).getAppName()  " + testlist.get(position).getAppName());

                            Log.d(TAG, "onClick: testlist.get(position).getPackageName()  " + testlist.get(position).getPackageName());
                            pos = position;
                            dialogs.dismiss();
                            String savelist = SPUtils.getString("applist", "");
                            Log.d(TAG, "onClick: savelist  " + savelist);
                            List<AppInfoss> saveL = new ArrayList<>();
                            if (TextUtils.isEmpty(savelist)) {
                                AppInfoss appInfoss = new AppInfoss();
                                appInfoss.setAppName(testlist.get(position).getAppName());
                                appInfoss.setPackageName(testlist.get(position).getPackageName());
                                saveL.add(appInfoss);

                            } else {
                                List<AppInfoss> appInfosses = GsonUtils.getPersons(savelist, AppInfoss.class);
                                int index = -1;
                                for (int i = 0; i < appInfosses.size(); i++) {
                                    if (testlist.get(position).getAppName().equals(appInfosses.get(i).getAppName()) ||
                                            testlist.get(position).getPackageName().equals(appInfosses.get(i).getPackageName())) {
                                        index = i;
                                    }
                                }
                                if (index >= 0) {
                                    appInfosses.remove(index);
                                }

                                AppInfoss appInfoss = new AppInfoss();
                                appInfoss.setAppName(testlist.get(position).getAppName());
                                appInfoss.setPackageName(testlist.get(position).getPackageName());

                                appInfosses.add(appInfoss);
                                saveL.addAll(appInfosses);

                            }

                            String s2 = new Gson().toJson(saveL);
                            SPUtils.putString("applist", s2);


                            String s = SPUtils.getString("applist", "");
                            Log.e("接收appinfo", "onMessageEvent: " + s);
                            List<AppInfoss> appInfosses = GsonUtils.getPersons(s, AppInfoss.class);
                            newallApp = new ArrayList<>();
                            if (appInfosses != null && appInfosses.size() > 0) {
                                for (int i = 0; i < appInfosses.size(); i++) {
                                    for (int j = 0; j < allApp.size(); j++) {
                                        if (allApp.get(j).getAppName().equals(appInfosses.get(i).getAppName()) ||
                                                allApp.get(j).getPackageName().equals(appInfosses.get(i).getPackageName())) {
                                            newallApp.add(allApp.get(j));
                                        }
                                    }
                                }
                            }

                            if (position<=9){
                                AppInfo appInfos = new AppInfo();
                                appInfos.setAppIcon(getResources().getDrawable(R.drawable.ic_add));
                                newallApp.add(appInfos);
                            }


                            //                           allMyAdapater = new UtilsAppAdapter(getContext(), newallApp);
                            //                           app_recycle.setAdapter(allMyAdapater);
                            allMyAdapater.setMlist(newallApp);


                        }


                    });

                } else {
                    MainActivity3.isShowOne = true;
                    MainActivity3.oneFramgent.chushihua();
                    //这里通过包名来跳转
                    Intent mIntent = new Intent();
                    PackageManager packageManager = getActivity().getPackageManager();
                    AppInfo appInfo = newallApp.get(position);
                    mIntent = packageManager.getLaunchIntentForPackage(appInfo.getPackageName());
                    mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (mIntent != null) {
                        startActivity(mIntent);
                    }
                    saveAppClick(appInfo.getPackageName());
                }
            }
        });
        //长按卸载apk，但是我这里没有做刷新的操作，需要注意一下
        allMyAdapater.setOnItemLongClickListener(new UtilsAppAdapter.OnItemLongClickListener() {
            @Override
            public void onClick(int position) {
                showMyDialog(position);
            }
        });
    }

    //默认显示主页面4个快捷方式
    private void initQuickApp() {
        String savelist = SPUtils.getString("applist", "");
        Log.d(TAG, "onClick: savelist  " + savelist);
        if (TextUtils.isEmpty(savelist)) {
            List<AppInfoss> saveL = new ArrayList<>();
            AppInfoss appInfoss = new AppInfoss();
            appInfoss.setAppName("相机");
            appInfoss.setPackageName("com.android.camera2");
            AppInfoss appInfoss2 = new AppInfoss();
            appInfoss2.setAppName("计算器");
            appInfoss2.setPackageName("com.android.calculator2");

            saveL.add(appInfoss);
            saveL.add(appInfoss2);

            String s2 = new Gson().toJson(saveL);
            SPUtils.putString("applist", s2);


            String ss = SPUtils.getString("applist", "");
            Log.e("接收appinfo", "onMessageEvent: " + ss);
            List<AppInfoss> appInfossess = GsonUtils.getPersons(ss, AppInfoss.class);
            newallApp = new ArrayList<>();
            if (appInfossess != null && appInfossess.size() > 0) {
                for (int i = 0; i < appInfossess.size(); i++) {
                    for (int j = 0; j < allApp.size(); j++) {
                        if (allApp.get(j).getAppName().equals(appInfossess.get(i).getAppName()) ||
                                allApp.get(j).getPackageName().equals(appInfossess.get(i).getPackageName())) {
                            newallApp.add(allApp.get(j));
                        }
                    }
                }
            }
        }
    }


    private void showMyDialog(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("提示");
        builder.setMessage("是否确定删除？");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int o) {
                dialogInterface.dismiss();

                //       ToastUtils.show("列表长按事件----------------");
                AppInfo appInfo = newallApp.get(position);
//                uninstall(appInfo.getPackageName());

                String savelist = SPUtils.getString("applist", "");
                List<AppInfoss> appInfosses2 = GsonUtils.getPersons(savelist, AppInfoss.class);
                int index = -1;
                //        ToastUtils.show("列表长按事件-------appInfosses2---------"+appInfosses2.size());
                for (int i = 0; i < appInfosses2.size(); i++) {
                    if (newallApp.get(position).getAppName().equals(appInfosses2.get(i).getAppName()) ||
                            newallApp.get(position).getPackageName().equals(appInfosses2.get(i).getPackageName())) {
                        index = i;
                    }
                }
                if (index >= 0) {
                    //       ToastUtils.show("列表长按事件-------remove---------"+index);
                    appInfosses2.remove(index);
                    //       ToastUtils.show("列表长按事件-----remove-appInfosses2---"+appInfosses2.size());
                    String s2 = new Gson().toJson(appInfosses2);
                    SPUtils.putString("applist", s2);
                }


                String s = SPUtils.getString("applist", "");
                Log.e("接收appinfo", "onMessageEvent: " + s);
                List<AppInfoss> appInfosses = GsonUtils.getPersons(s, AppInfoss.class);
                newallApp = new ArrayList<>();
                if (appInfosses != null && appInfosses.size() > 0) {
                    for (int i = 0; i < appInfosses.size(); i++) {
                        for (int j = 0; j < allApp.size(); j++) {
                            if (allApp.get(j).getAppName().equals(appInfosses.get(i).getAppName()) ||
                                    allApp.get(j).getPackageName().equals(appInfosses.get(i).getPackageName())) {
                                newallApp.add(allApp.get(j));
                            }
                        }
                    }
                }
                AppInfo appInfos = new AppInfo();
                appInfos.setAppIcon(getResources().getDrawable(R.drawable.ic_add));
                newallApp.add(appInfos);

                //   ToastUtils.show("chishihua长按------------------"+newallApp.size());
                allMyAdapater.setMlist(newallApp);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }


    public boolean uninstall(String packageName) {
        boolean b = checkApplication(packageName);
        if (b) {
            Uri packageURI = Uri.parse("package:".concat(packageName));
            Intent intent = new Intent(Intent.ACTION_DELETE);
            intent.setData(packageURI);
            this.startActivity(intent);
            return true;
        }
        return false;
    }

    private boolean checkApplication(String packageName) {
        if (packageName == null || "".equals(packageName)) {
            return false;
        }
        return true;
    }


    private int getWeek() {


        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        weekday = c.get(Calendar.DAY_OF_WEEK);
//        if (weekday == 1) {
//            week = "周日";
//
//        } else if (weekday == 2) {
//            week = "周一";
//
//        } else if (weekday == 3) {
//            week = "周二";
//
//        } else if (weekday == 4) {
//            week = "周三";
//
//        } else if (weekday == 5) {
//            week = "周四";
//
//        } else if (weekday == 6) {
//            week = "周五";
//
//        } else if (weekday == 7) {
//            week = "周六";
//
//        }
        return weekday;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_tab1:
                Log.d(TAG, "onClick: ll_tab1");
                MainActivity3.isShowOne = true;

                intent = new Intent();
                ComponentName cn = new ComponentName("com.wjlocal.whiteboard", "com.wjlocal.whiteboard.ui.activity.HomeActivity");
                intent.setComponent(cn);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);


                saveAppClick("com.wjlocal.whiteboard");

                break;
            case R.id.ll_tab2:
                Log.d(TAG, "onClick: ll_tab2");
                MainActivity3.isShowOne = true;

                intent = getActivity().getPackageManager().getLaunchIntentForPackage("com.hikeen.filemanager");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

                saveAppClick("com.hikeen.filemanager");
                break;
            case R.id.ll_tab3:
                Log.d(TAG, "onClick: ll_tab3");
                MainActivity3.isShowOne = true;
                intent = getActivity().getPackageManager().getLaunchIntentForPackage("com.ecloud.eshare.server");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
//                ComponentName cn1 = new ComponentName("com.ecloud.eshare.server", "com.eshare.server.register.RegisterActivity");
//                intent.setComponent(cn1);
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);

//                saveAppClick("com.bozee.andisplayguide");
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage event) {
        // Do something

        if (event.getMessage().equals("selectapp")) {
            DialogUIUtils.dismiss(dialogs);

            allApp.add(allApp.size() - 1, testlist.get(pos));
            allMyAdapater = new UtilsAppAdapter(getContext(), allApp);

            app_recycle.setAdapter(allMyAdapater);

            allMyAdapater.setOnItemClickListener(new UtilsAppAdapter.OnItemClickListener() {
                @Override
                public void onClick(int position) {
                    Log.e("dsadsadsa", "dsadsadsa: " + position + "-------------------" + (allApp.size() - 1));
                    if (position == allApp.size() - 1) {
                        //最后一跳点击添加
                        // ToastUtils.show("最后一条 添加");
                        //自定义弹框
                        View rootView = View.inflate(getContext(), R.layout.layout_app_sel, null);
                        RecyclerView recycle = rootView.findViewById(R.id.recycle);
                        linearLayoutManager = new LinearLayoutManager(getContext());
                        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
                        recycle.setLayoutManager(linearLayoutManager);
                        //需要过滤掉想要加入的APP列表  到这里
                        testlist = AppUtils.getAppInfo1(getContext());
                        AppSelectAdapter appSelectAdapter = new AppSelectAdapter(mcontext, testlist);
                        recycle.setAdapter(appSelectAdapter);
                        dialogs = DialogUIUtils.showCustomAlert(getContext(), rootView).show();

                        appSelectAdapter.setOnItemClickListener(new AppSelectAdapter.OnItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                pos = position;
                            }
                        });


                    } else {
                        //这里通过包名来跳转
                        Intent mIntent = new Intent();
                        PackageManager packageManager = getActivity().getPackageManager();
                        AppInfo appInfo = allApp.get(position);
                        mIntent = packageManager.getLaunchIntentForPackage(appInfo.getPackageName());
                        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (mIntent != null) {
                            startActivity(mIntent);
                        }
                    }
                }
            });
            //长按卸载apk，但是我这里没有做刷新的操作，需要注意一下
            allMyAdapater.setOnItemLongClickListener(new UtilsAppAdapter.OnItemLongClickListener() {
                @Override
                public void onClick(int position) {
                    AppInfo appInfo = allApp.get(position);
                    uninstall(appInfo.getPackageName());
                }
            });

        }

        if (event.getType() == 12) {
            if (event.getMessage().equals("refreshlist")) {
                chushihua();
            }
        }

    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void saveAppClick(String pack) {
        //这里通过包名来获取app名
        String name = "";
        PackageInfo packageInfo = null;
        PackageManager packageManager = getActivity().getPackageManager();
        try {
            packageInfo = packageManager.getPackageInfo(pack, PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        name = packageInfo.applicationInfo.loadLabel(packageManager).toString();
        String finalName = name;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000); // 休眠1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String s = FileImageUtils.savefilePath(getContext(), finalName);
                File filePic = new File(s);
                filePic.getParentFile().mkdirs();
                screenShotByShell(s);

            }
        }).start();
        //保存当前打开的APP  到第一条
        String savelist = SPUtils.getString("savelist", "");
        List<AppInfoss> saveL = new ArrayList<>();
        if (TextUtils.isEmpty(savelist)) {
            AppInfoss appInfoss = new AppInfoss();
            appInfoss.setAppName(name);
            appInfoss.setPackageName(pack);
            saveL.add(appInfoss);
        } else {
            List<AppInfoss> appInfosses = GsonUtils.getPersons(savelist, AppInfoss.class);
            int index = -1;
            for (int i = 0; i < appInfosses.size(); i++) {
                if (name.equals(appInfosses.get(i).getAppName()) &&
                        pack.equals(appInfosses.get(i).getPackageName())) {
                    index = i;
                }
            }
            if (index >= 0) {
                appInfosses.remove(index);
            }
            AppInfoss appInfoss = new AppInfoss();
            appInfoss.setAppName(name);
            appInfoss.setPackageName(pack);
//            if (appInfosses.size()>7){
//                appInfosses.remove(appInfosses.size()-1);
//                appInfosses.add(0,appInfoss);
//            }else {
            appInfosses.add(0, appInfoss);
//            }
            saveL.addAll(appInfosses);
        }
        String s = new Gson().toJson(saveL);
        Log.e("appinfo", "onClick: " + s);
        SPUtils.putString("savelist", s);
    }

    //    三、使用screencap的adb命令
//
//    命令行是这样的：adb shell screencap -p file_path
//
//    在代码中执行，就不用adb shell，直接screencap -p file_path，调用Runtime的进程来执行：

    public void screenShotByShell(String filePath) {
        String shotCmd = "screencap -p " + filePath + " \n";
        try {
            Runtime.getRuntime().exec(shotCmd);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
